<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="滞留件编号" prop="retNumber">
        <el-input
          v-model="queryParams.retNumber"
          placeholder="请输入滞留件编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货架编号" prop="shelfNumber">
        <el-input
          v-model="queryParams.shelfNumber"
          placeholder="请输入货架编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓位编号" prop="positionNumber">
        <el-input
          v-model="queryParams.positionNumber"
          placeholder="请输入仓位编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上架备注" prop="listNotes">
        <el-input
          v-model="queryParams.listNotes"
          placeholder="请输入上架备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户编号" prop="userAccount">
        <el-input
          v-model="queryParams.userAccount"
          placeholder="请输入客户编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上架日期" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择上架日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="下架日期" prop="overTime">
        <el-date-picker clearable
          v-model="queryParams.overTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择下架日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="处理状态" prop="handleStatus">
        <el-select v-model="queryParams.handleStatus" placeholder="请选择处理状态" clearable>
          <el-option
            v-for="dict in dict.type.handle_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销毁时间" prop="destroyTime">
        <el-date-picker clearable
          v-model="queryParams.destroyTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择销毁时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="retshelfAdd"
          v-hasPermi="['system:retshelf:add']"
        >滞留件上架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:retshelf:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:retshelf:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:retshelf:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="retshelfList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="滞留件编号" align="center" prop="retNumber" />
      <el-table-column label="订单编号" align="center" prop="orderNumber" />
      <el-table-column label="货架编号" align="center" prop="shelfNumber" />
      <el-table-column label="仓位编号" align="center" prop="positionNumber" />
      <el-table-column label="上架备注" align="center" prop="listNotes" />
      <el-table-column label="客户编号" align="center" prop="userAccount" />
      <el-table-column label="上架日期" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下架日期" align="center" prop="overTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.overTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理状态" align="center" prop="handleStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.handle_status" :value="scope.row.handleStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="销毁时间" align="center" prop="destroyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.destroyTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:retshelf:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:retshelf:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改滞留件管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="滞留件编号" prop="retNumber">
          <el-input v-model="form.retNumber" placeholder="请输入滞留件编号" />
        </el-form-item>
        <el-form-item label="订单编号" prop="orderNumber">
<!--          <el-input v-model="form.orderNumber" placeholder="请输入订单编号" />-->
          <el-select v-model="form.orderNumber" filterable placeholder="请选择" @change="handleClientChange">
            <el-option v-for="item in notInOrder" :key="item.id" :label="item.orderNumber" :value="item.orderNumber" >
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="货架编号" prop="shelfNumber">
          <el-input v-model="form.shelfNumber" placeholder="请输入货架编号" />
        </el-form-item>
        <el-form-item label="仓位编号" prop="positionNumber">
<!--          <el-input v-model="form.positionNumber" placeholder="请输入仓位编号" />-->
          <el-select v-model="form.positionNumber" filterable placeholder="请选择" @change="handleCangChange">
            <el-option v-for="item in zhiLiuCang" :key="item.id" :label="item.positionNumber" :value="item.positionNumber" >
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="上架备注" prop="listNotes">
          <el-input v-model="form.listNotes" placeholder="请输入上架备注" />
        </el-form-item>
        <el-form-item label="客户编号" prop="userAccount">
          <el-input v-model="form.userAccount" placeholder="请输入客户编号" :disabled = "true"/>
        </el-form-item>
        <el-form-item label="上架日期" prop="createTime">
          <el-date-picker clearable
                          v-model="form.createTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择上架日期">
          </el-date-picker>
        </el-form-item>
<!--        <el-form-item label="下架日期" prop="overTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.overTime"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="请选择下架日期">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="处理状态" prop="handleStatus">-->
<!--          <el-select v-model="form.handleStatus" placeholder="请选择处理状态">-->
<!--            <el-option-->
<!--              v-for="dict in dict.type.handle_status"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--:value="parseInt(dict.value)"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="销毁时间" prop="destroyTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.destroyTime"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="请选择销毁时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitOnForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRetshelf, getRetshelf, delRetshelf, addRetshelf, updateRetshelf } from "@/api/system/retshelf";
import {listInfo, updateInfo} from "@/api/system/info";
import {listPosition} from "@/api/system/position";

export default {
  name: "Retshelf",
  dicts: ['handle_status'],
  data() {
    return {
      //订单列表
      orderTypeselectoption: [],
      //未入库订单列表
      notInOrder: [],
      //仓位列表
      cangWei: [],
      //滞留仓列表
      zhiLiuCang: [],


      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 滞留件管理表格数据
      retshelfList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        retNumber: null,
        orderNumber: null,
        shelfNumber: null,
        positionNumber: null,
        listNotes: null,
        userAccount: null,
        createTime: null,
        overTime: null,
        handleStatus: null,
        destroyTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        retNumber: [
          { required: true, message: "滞留件编号不能为空", trigger: "blur" }
        ],
        orderNumber: [
          { required: true, message: "订单编号不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    console.log('开始获取仓位数据');
    listPosition().then(res => {
      console.log('仓位数据:', res);
    }).catch(err => {
      console.error('获取仓位数据出错:', err);
    });
  },
  methods: {
    handleCangChange(selectedshelfNumber) {
      // 在选项数组中查找匹配的货架
      const selectedShelf = this.zhiLiuCang.find(
        item => item.positionNumber === selectedshelfNumber
      );

      // 如果找到匹配项则设置客户名称
      if (selectedShelf) {
        this.form.shelfNumber = selectedShelf.shelfNumber;

      }

    },
    handleClientChange(selectedshelfNumber) {
      // 在选项数组中查找匹配的货架
      const selectedShelf = this.notInOrder.find(
        item => item.orderNumber === selectedshelfNumber
      );

      // 如果找到匹配项则设置客户名称
      if (selectedShelf) {
        this.form.userAccount = selectedShelf.userName;
        // this.form.warNumber = selectedShelf.warNumber;
      //   if (selectedShelf.shelfType === 0) {
      //     this.form.positionType = 0;
      //   }
      //   else if (selectedShelf.shelfType === 1){
      //     this.form.positionType = 1;
      //   }
      //   else if (selectedShelf.shelfType === 2){
      //     this.form.positionType = 2;
      //   }
      // } else {
      //   this.form.shelfNumber = ""; // 没有匹配项时清空
      }
    },

    /** 查询滞留件管理列表 */
    getList() {
      this.loading = true;
      listRetshelf(this.queryParams).then(response => {
        this.retshelfList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

      listInfo().then((res) => {
        this.orderTypeselectoption = res.rows
        this.notInOrder = this.orderTypeselectoption.filter(item => {
          return item.storeStatus === 2;
        });
      });

      listPosition().then((res) => {
        this.cangWei = res.rows
        this.zhiLiuCang = this.cangWei.filter(item => {
          return item.positionType === 2;
        });
      }).catch(error => {
        console.error('获取仓位数据失败:', error);
        this.$message.error('获取仓位数据失败');
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        retNumber: null,
        orderNumber: null,
        shelfNumber: null,
        positionNumber: null,
        listNotes: null,
        userAccount: null,
        createTime: null,
        overTime: null,
        handleStatus: null,
        destroyTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 上架按钮操作 */
    retshelfAdd() {
      this.reset();
      this.open = true;
      this.title = "添加滞留件管理";
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加滞留件管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRetshelf(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改滞留件管理";
      });
    },
    /** 提交上架按钮 */
    submitOnForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRetshelf(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.handleStatus = 0; //0-上架 1-销毁 2-下架

            //BUG：时间一直是错的
            addRetshelf(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");

              //更新订单表
              const selectedOrder = this.orderTypeselectoption.find(
                item => item.orderNumber === this.form.orderNumber
              );
              const orderForm = {
                id: selectedOrder.id,
                orderNumber: selectedOrder.orderNumber,
                orderType: selectedOrder.orderType,
                orderStatus: selectedOrder.orderStatus,
                storeStatus: 0,
                storeTime: this.form.createTime,
                orderCreateTime: selectedOrder.orderCreateTime,

                packStatus: selectedOrder.packStatus,

                outboundStatus: selectedOrder.outboundStatus,
                stocktakingStatus: selectedOrder.stocktakingStatus,
                sendStatus: selectedOrder.sendStatus,
                userName: selectedOrder.userName
              };
              updateInfo(orderForm);

              //更新入库表
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRetshelf(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRetshelf(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除滞留件管理编号为"' + ids + '"的数据项？').then(function() {
        return delRetshelf(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/retshelf/export', {
        ...this.queryParams
      }, `retshelf_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
